package com.freewater.javabase.demo.network.proxy;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

public class ProxyUseProxyClass {

    public static void main(String[] args) throws IOException {
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 1080);
        Proxy proxy = new Proxy(Proxy.Type.SOCKS, inetSocketAddress);
        URL url = new URL("https://www.google.com");
        readContent(url, proxy);
    }

    private static void readContent(URL url, Proxy proxy) throws IOException {
        final URLConnection urlConnection = url.openConnection(proxy);
        urlConnection.setConnectTimeout(10 * 1000);
        try (final InputStream inputStream = urlConnection.getInputStream();
             final ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            int read = -1;
            byte[] bytes = new byte[1024];
            while ((read = inputStream.read(bytes)) != -1) {
                bos.write(bytes);
            }
            bos.flush();
            final String content = bos.toString(Charset.forName("utf-8"));
            System.out.println(content.substring(0, 100));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
